package com.example.supermarket.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * <p>登录拦截器</p>
 * @author Bosen
 * @date 2021/10/10 23:05
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求
        String uri = request.getRequestURI();
        String member = "/member[\\d\\w\\S]*";
        Pattern memberPattern = Pattern.compile(member);
        if(memberPattern.matcher(uri).matches()){
            // member
            Object user = request.getSession().getAttribute("member");
            if (user == null) {
                // 获取request返回页面到登录页
                request.getRequestDispatcher("/member/login").forward(request, response);
                return false;
            }
        }else{
            // admin
            Object user = request.getSession().getAttribute("admin");
            if (user == null) {
                // 获取request返回页面到登录页
                request.getRequestDispatcher("/admin/login").forward(request, response);
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}
}